package com.wwx.worldonwheels.common.config;

/**
 * ClassName: df
 * Description:
 * CreatedBy: HuaHX
 */

/**
 * ClassName: ControllerAdvice
 * Description:
 * CreatedBy: HuaHX
 */

import com.wwx.worldonwheels.common.result.CommonResult;
import lombok.extern.slf4j.Slf4j;

import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.sql.SQLException;


/**
 * 全局异常处理
 *
 * @author hjr
 */
@RestControllerAdvice
public class CommonExceptionHandler {

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CommonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder sb = new StringBuilder("校验失败:");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getField()).append("：").append(fieldError.getDefaultMessage()).append(", ");
        }
        String msg = sb.toString();
        return CommonResult.failed(msg);
    }

    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CommonResult handleConstraintViolationException(ConstraintViolationException ex) {
        return CommonResult.failed(ex.getMessage());
    }

    @ExceptionHandler(SQLException.class)
    public CommonResult mySqlException(SQLException e){
    return CommonResult.failed(e.getMessage());
    }

    @ExceptionHandler(ServletRequestBindingException.class)
    public CommonResult requestException(ServletRequestBindingException e){
        return CommonResult.failed(e.getMessage());
    }


    @ExceptionHandler(NullPointerException.class)
    public CommonResult nullPointer(NullPointerException e){
        return CommonResult.failed(e.getMessage());
    }

}